package demo_lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: android 超级兵
 * @create: 2022-01-17 16:32
 * TODO 可重入锁
 **/
public class ReentryLockClient {
    private int count = 0;
    private int countLength = 1000 * 100;

    private Lock lock = new ReentrantLock();

    private class ThreadA extends Thread {
        @Override
        public void run() {
            super.run();
            addCount();
        }
    }

    private void addCount() {
        for (int i = 0; i < countLength; i++) {
            lock.lock();
            try {
                count++;
            } finally {
                lock.unlock();
            }
        }
    }

    private class ThreadB extends Thread {
        @Override
        public void run() {
            super.run();
            addCount();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReentryLockClient reentryLockClient = new ReentryLockClient();
        reentryLockClient.build();
    }

    private void build() throws InterruptedException {
        new ThreadA().start();
        new ThreadB().start();

//        test();
        Thread.sleep(100);
        System.out.println("count为:" + count);
    }

    /*
     * @author: android 超级兵
     * @create: 2022/1/17 16:40
     * TODO 具有可重入性
     */
    public synchronized void test() {
        count++;
        if (count <= 10) {
            test();
        }
    }
}
